<template>
	<view class="container">
		<!-- TODO 嵌入地图显示当前位置 -->
		<form @reset="formReset">
			<uform v-model="form" ref="uform" :config="config" :rules="rules" :showBorder="showBorder" label-position="left">
				<template #casePosDesc>
					<uni-easyinput suffixIcon="location-filled" v-model="form.casePosDesc" placeholder="点击选择具体位置"  @iconClick="posClick"></uni-easyinput>
				</template>
			</uform>
			<view class="uni-btn-v" style="display: flex;padding:20px;">
				<button type="primary" @click="formSubmitBefore(0)">保存</button>
				<button type="primary" @click="formSubmitBefore(1)">提交</button>
				<button type="default" form-type="reset">重置</button>
			</view>
		</form>
	</view>
</template>

<script>
	import uform from '@/components/uni-uform/uni-uform.vue'
	import { listAmCaseTypeAll, listAmCaseType } from "@/api/dums/gov/caseType/caseType";
	import {addCawCaseAccept} from "@/api/dums/caw/cawAccept";
	import {uuid} from "@/plugins/package/utils";
	import { listOrg } from "@/api/system/org";
	import { getToken } from '@/utils/auth';
	import  configs from '@/config'
	export default {
		data(){
			return {
				caseId: uuid(16),
				form:{
					rptChannelId:null,
					occurTime:null,
				},
				config:[{
					name: 'occurTime',
					label: '发生时间',
					component: 'uni-datetime-picker',
					required:true,
					extra:{
					}
				},{
					name: 'caseOrgId',
					label: '问题归属',
					component: 'uni-data-select',
					required:true,
					init(){
						if(!this.extra){
							this['extra']={localdata:[]};
						}
						if(!this.extra.localdata){
							this.extra['localdata'] = [];
						}
						listOrg({type:6}).then(res => {
							if(res.data){
								for (const key in res.data) {
									this.extra.localdata.push({
										text:res.data[key].displayName,
										value:res.data[key].id
									});
								}
							}
						});
					}
				},{
					name: 'caseGrade',
					label: '问题级别',
					component: 'uni-data-select',
					required:true,
					extra: {
						dict:"case_level",
						localdata: [{text:"事件",value:"00"},{text:"部件",value:"10"}]
					},
				},{
					name: 'caseType',
					label: '问题类型',
					component: 'uni-data-checkbox',
					required:true,
					extra: {
						localdata: []
					},
					init(){
						if(!this.extra){
							this['extra']={localdata:[]};
						}
						if(!this.extra.localdata){
							this.extra['localdata'] = [];
						}
						this.extra.localdata=[];
						listAmCaseTypeAll({parentId: "00"}).then(res=>{
							if(res){
								res.map(item=>{
									this.extra.localdata.push({
										text:item.caseTypeName,
										value:item.caseTypeId
									});
								});
							}
						});
					},
					event:{
						change:(e)=>{
							listAmCaseTypeAll({params:{caseType:e.detail.value}}).then(res=>{
								for(let i=0;i<res.length;i++){
									res[i].text = res[i].caseTypeName;
									res[i].value = res[i].caseTypeId;
								}
								let {item} = this.getItem("caseTypes");
								item.extra.localdata = this.handleTree(res, "caseTypeId");
							});
						}
					}
				},{
					name: 'caseTypes',
					label: '案件类型',
					component: 'uni-data-picker',
					required:true,
					extra:{
						localdata:[]
					},
					event:{
						change:(e)=>{
							console.log(e.detail.value);
							let {item}=this.getItem("caseTypes");
							this.form.caseTypes=e.detail.value;
						}
					}
				},{
					name: 'rptUserName',
					label: '上报人',
					component: 'uni-easyinput',
					required:true,
					extra:{
						placeholder: "请输入上报人",
					}
				},{
					name: 'rptPhone',
					label: '联系电话',
					component: 'uni-easyinput',
					required:true,
					extra:{
						placeholder: "请输入联系电话",
					}
				},{
					name: 'caseDesc',
					label: '问题描述',
					component: 'uni-easyinput',
					required:true,
					extra:{
						type: "textarea",
						placeholder: "请输入问题描述",
					}
				},{
					name: 'casePosDesc',
					label: '地址描述',
					component: 'uni-easyinput',
					required:true,
					isSlot:true,
					extra:{
						type: "textarea",
						placeholder: "请输入地址描述",
					}
				},{
					name: 'ssqy',
					label: '所属区域',
					component: 'uni-data-picker',
					required:true,
					extra:{
						localdata:[]
					},
					event:{
						change:(e)=>{
							console.log(e.detail.value)
							let {item} = this.getItem("ssqy");
							this.form.ssqy = e.detail.value;
						}
					},
					init:()=>{
						listOrg({type:0}).then(res =>{
							if(res.data){
								for(let i=0;i<res.data.length;i++){
									res.data[i].text = res.data[i].displayName;
									res.data[i].value = res.data[i].id;
								}
								let {item} = this.getItem("ssqy");
								item.extra.localdata = this.handleTree(res.data, "id");
							}
						});
					}
				},{
					name: 'sswg',
					label: '所属网格',
					component: 'uni-data-select',
					extra:{
						style:"border:none;",
					}
				},{
					name: 'images',
					label: '附件',
					component: 'uni-file-picker',
					extra: {
						"auto-upload":false,
						ref:"files",
						limit:3,
						title:"最多选择3张图片",
						fileMediatype:"image"
					},
					event:{
						success:(e)=>{
							console.log(e);
						},
						select:(e)=>{
							for (let i = 0; i < e.tempFilePaths.length; i++) {
								this.filePaths.push(e.tempFilePaths[i]);
							}
						},
						delete:(e)=>{
							for (let i = 0; i < this.filePaths.length; i++) {
								if (this.filePaths[i] == e.tempFilePath) {
									this.filePaths.splice(i, 1);
								}
							}
						},
					}
				}],
				showBorder:true,
				rules:{
					rptChannelId:{
						rules:[
							{required: true, errorMessage: "问题来源不能为空"}
						],
					},
					occurTime:{
						rules:[
							{required: true, errorMessage: "发生时间不能为空"}
						],
					},
					caseOrgId:{
						rules:[
							{required: true, errorMessage: "问题归属不能为空"}
						],
					},
					caseType:{
						rules:[
							{required: true, errorMessage: "问题类型不能为空"}
						],
					},
					caseGrade:{
						rules:[
							{required: true, errorMessage: "问题级别不能为空"}
						],
					},
					caseTypes:{
						rules:[
							{required: true, errorMessage: "案件类型不能为空"}
						],
					},
					rptUserName:{
						rules:[
							{required: true, errorMessage: "上报人不能为空"}
						],
					},
					rptPhone:{
						rules:[
							{required: true, errorMessage: "请输入正确联系电话"}
						],
					},
					caseDesc:{
						rules:[
							{required: true, errorMessage: "问题描述不能为空"}
						],
					},
					casePosDesc:{
						rules:[
							{required: true, errorMessage: "地址描述不能为空"}
						],
					},
					ssqy:{
						rules:[
							{required: true, errorMessage: "所属区域不能为空"}
						],
					},
				},
				filePaths:[],
			}
		},
		components: {
			uform,
		},
		mounted(){
			
		},
		methods:{
			getItem(name) {
				return {
					item: this.config.find(res => res.name === name),
					index: this.config.findIndex(res => res.name === name)
				}
			},
			posClick(){
				let _this = this;
				//跳转位置选择页面
				uni.navigateTo({
					url:"../../common/webview/index?aurl="+encodeURI("pages/position"),
					events:{
						//监听选点事件，得到坐标 详细地址
						acceptDataFromOpenedPage:function(data){
							_this.form.casePosDesc = data.coordinate.address;
							_this.form.lnglat = data.coordinate.lon+","+data.coordinate.lat;
						}
					}
				})
			},
			fileUpload(caseId,linkName,runId){
				return new Promise((resolve,reject) => {
					this.filePaths.forEach(file => {
						uni.uploadFile({
							url: configs.baseUrl+'/caw/caseAttach/uploadCaseAndSaveTheFile', //仅为示例，非真实的接口地址
							filePath: file,
							name: 'file',
							header:{
								"Authorization": "Bearer " + getToken() 
							},
							formData: {
								caseId:caseId,
								linkName:linkName,
								runId:runId
							},
							success: (uploadFileRes) => {
								resolve()
							},
							fail() {
								reject()
							}
						});
					})
				})
			},
			formSubmitBefore: function(type) {
				// console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
				console.log(type);
			    //定义表单规则
				let form = this.$refs.uform.getForm()
				form.validate().then(res => {
					console.log('表单数据信息：', res);
					
					this.form.caseId=this.caseId;
					this.form.rptTime = new Date().getTime();
					this.form.operCode = type==1?"O01":"O00";  //O00 保存登记 O01提交上报
					this.form.reportType = "N";  //N-普通上报;F-快速上报;A-自处置上报
					if(this.form.caseTypes[1]){
						this.form.caseTypeLevel1 = this.form.caseTypes[1].value;
					}
					if(this.form.caseTypes[2]){
						this.form.caseTypeLevel2 = this.form.caseTypes[2].value;
					}
					if(this.form.caseTypes[3]){
						this.form.caseTypeLevel3 = this.form.caseTypes[3].value;
					}
					if(this.form.ssqy[0]){
						this.form.regionName = this.form.ssqy[0].text;
						this.form.regionId = this.form.ssqy[0].value;
					}
					if(this.form.ssqy[1]){
						this.form.streetName = this.form.ssqy[1].text;
						this.form.streetId = this.form.ssqy[1].value;
					}
					if(this.form.ssqy[2]){
						this.form.communityName = this.form.ssqy[2].text;
						this.form.communityId = this.form.ssqy[2].value;
					}
					if(this.form.zczChecked){
						this.form.reportType = "A";
					}
					// if(this.lngLat.lng){
					// 	this.form.posX = this.lngLat.lng;
					// 	this.form.posY = this.lngLat.lat;
					// }
					if(this.filePaths.length>0){
						this.fileUpload(this.caseId,"问题登记",0).then(res=>{
							this.formSubmit();
						});
					}else{
						this.formSubmit();
					}
					console.log('表单数据信息：', this.form);
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			formReset: function(e) {
				console.log('清空数据')
				this.form={}
			},
			formSubmit:function(){
				this.form.rptChannelId = '1106'
				addCawCaseAccept(this.form).then(res=>{
					console.log(res);
					if(res.code==200){
						uni.showModal({
							title: '提示', // 标题
							content: '上报成功', // 提示内容
							showCancel: false, 
							success(res) {
								uni.navigateBack(0)
							}
						});		
					}else{
						uni.showToast({
							duration: 3000,
							icon: "error",
							title:res.msg
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.uni-form-item{
		display: flex;
		align-items: center;
		padding: 10px 15px;
		border-bottom: 1px solid #eee;
	}
	.uni-form-item .title{
		width:30%;
	}
	.uni-form-item .content{
		width:70%;
	}
</style>